package top.scsoul.voes.framework.config;

import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.scsoul.voes.common.core.domain.AjaxResult;
import top.scsoul.voes.common.exception.SystemException;

import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice
public class RestAdviceConfig {
    @ExceptionHandler(SystemException.class)
    public AjaxResult runtimeExceptionHandler(RuntimeException e) {
        return AjaxResult.error(e.getMessage());
    }

    @ExceptionHandler(SQLException.class)
    public AjaxResult sQLException(SQLException e) {
        e.printStackTrace();
        return AjaxResult.error("数据异常");
    }

    @ExceptionHandler(ExpiredJwtException.class)
    public AjaxResult expiredJwtException(ExpiredJwtException e, HttpServletResponse response) {
        response.setStatus(401);
        e.printStackTrace();
        return AjaxResult.error("token过期");
    }

    @ExceptionHandler(BindException.class)
    public AjaxResult bindException(BindException e, HttpServletResponse response) {
        ArrayList<String> arrayList = new ArrayList<>();
        if (e.getErrorCount() > 0) {
            List<FieldError> fieldErrors = e.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                arrayList.add(fieldError.getDefaultMessage());
            }
        }
        String err = arrayList.toString().replace("[", "").replace("]", "");
        return AjaxResult.error(0, err);
    }
}
